<?php


namespace App\Services;

use App\Admin\Actions\Post\TransverseBillPost;
use App\Admin\Actions\Post\TransverseFileImport;
use App\Admin\Actions\Review\TransverseReview;
use App\Extensions\Exporters\TransverseExporter;
use App\Extensions\LayerRowAction;
use App\Extensions\Renderable\TransverseBillRenderable;
use App\Extensions\Renderable\TransverseBuyerRenderable;
use App\Extensions\Renderable\TransverseDetailRenderable;
use App\Models\AdminUser;
use App\Repositories\TransverseRepository;
use App\Services\Common\Enum;
use App\Setting;
use App\Transverse;
use App\TransverseBill;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Database\Eloquent\Builder;

class TransverseService
{
    protected $repository;

    public function __construct()
    {
        $this->repository = $this->repository();
    }

    public function gridColumn(Grid $grid, $role = 0, $type = 0)
    {
        $admin_review_name = Setting::getReviewName(1);
        $grid->model()->when($role == 1, function ($query) {
            return $query->whereIn('review_status', [0, 1, 2]);
        })->when(request()->get('action') === 'reviewing', function ($query) {
            return $query->where('review_status', 0);
        })->orderByDesc('id');
        $grid->model()->with(['bills']);
        $grid->column('uuid', __('系统编号'));
        $grid->column('name', __('合同名称'))->modal('详情', TransverseDetailRenderable::class);
        if ($role == 1) {
            $grid->column('contract_no', __('合同登记号'))->editable();
        } else {
            $grid->column('contract_no', __('合同登记号'));
        }
        $grid->column('contract_type', __('合同类型'))->style('min-width:80px');
        $grid->column('user_name', __('负责人'))->width(80);
        $grid->column('department.name', __('dept_name'));
        $grid->column('buyer', __('甲方名称'))->modal('甲方', TransverseBuyerRenderable::class);
        $grid->column('buyer_unified_code', __('统一社会信用代码'));
        $grid->column('buyer_person', __('buyer_person'));
        $grid->column('buyer_phone', __('buyer_phone'));
        $grid->column('buyer_province', __('buyer_province'))->width(50);
        $grid->column('buyer_address', __('buyer_address'));
        $grid->column('amount', __('contract_amount'))->sortable();
        $grid->column('in_amount', __('received amount'))->modal('到账单', TransverseBillRenderable::class);
        $grid->column('domain', __('所属领域'));
        $grid->column('state', __('研究状态'))
            ->display(function ($state) {
                return $this->review_status == 1 ? $state : 2;
            })->using(['在研', '已结项', ''])->label(['info', 'success', '']);
        $grid->column('sign_date', __('签订时间'))->width(90);
        $grid->column('review_status', __('审批状态'))->using([
            $admin_review_name . '-待处理',
            $admin_review_name . '-通过',
            $admin_review_name . '-未通过',
            $admin_review_name . '-退回修改',
        ])->label(['warning', 'success', 'default', 'default']);
        $grid->column('end_time', '结项时间')->width(90);

        $grid->column('participants', '参加人员')->display(function ($value) {
            return $value ? sprintf("查看(%s)", count($value)) : '';
        })->modal('详情', function ($model) {
            return new Table(['姓名', '单位', '职称', '负责任务'], collect($model['participants'])->values()->all());
        })->width(80);
        $grid->column('created_at', __('Created at'))->display(function ($value) {
            return Carbon::parse($value)->toDateString();
        })->width(90);
        $grid->hideColumns(['buyer_phone', 'buyer_person', 'buyer_address', 'created_at', 'end_time']);
        $grid->filter(function (Grid\Filter $filter) use ($role, $type) {
            $filter->disableIdFilter();
            $filter->scope('review', '待审批')->where('review_status', 0);
            $filter->column(1 / 2, function (Grid\Filter $filter) use ($type) {
                $filter->where(function ($query) {
                    $query->where('uuid', 'like', "%{$this->input}%")
                        ->orWhere('contract_no', 'like', "%{$this->input}%")
                        ->orWhere('name', 'like', "%{$this->input}%")
                        ->orWhere('contract_type', 'like', "%{$this->input}%")
                        ->orWhere('buyer', 'like', "%{$this->input}%")
                        ->orWhere('domain', 'like', "%{$this->input}%")
                        ->orWhere('user_name', 'like', "%{$this->input}%");
                }, '关键字', 'keywords')->placeholder('编号/名称/类型/合同类型/所属领域/负责人');
                $filter->equal('department_id', __('dept_name'))->select(department_select_options());
                $filter->equal('contract_type', '合同类型')->select(project_contract_type_options());
                $filter->where(function ($query) {
                    $query->whereYear('sign_date', $this->input);
                }, '签订年份', 'sign_date')->year();
                $filter->equal('year', '年份')->year();
            });
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('review_status', '审批状态')->radio(['待审批', '通过', '未通过', '退回修改']);
                $filter->where(function ($query) {
                    $query->where('review_status', 1)->where('state', $this->input);
                }, '研究状态', 'state')->radio(['在研', '已结项']);
                $filter->equal('buyer_province', __('buyer_province'))->select(Enum::province());
//                $filter->between('sign_date', '签订时间')->date();
                $filter->where(function ($query) {
                    $query->whereYear('end_time', $this->input);
                }, '结项年份', 'end_year')->year();
            });
        });
        $grid->exporter(new TransverseExporter());
        $grid->actions(function (Grid\Displayers\Actions $actions) use ($role) {
            $model = $actions->row;
            $actions->disableView();
            if ($role == 1) {
                $actions->disableEdit();
                if ($model->review_status) {
                    $actions->prepend(new TransverseFileImport($actions));
                }
                $actions->prepend("<br/>");
                $actions->prepend(sprintf('<a href="%s/%s/edit" class="grid-row-edit">&nbsp;编辑&nbsp;</a>',
                    $actions->getResource(),
                    $model['id']
                ));
                if (!$model->review_status) {
                    $actions->prepend(new TransverseReview($actions));
                } elseif ($model->review_status == 1) {
                    if ($model['amount'] > $model['in_amount']) {
                        $actions->prepend(new TransverseBillPost($actions));
                    }
                    if ($model->state != 1) {
                        $actions->prepend(new LayerRowAction(admin_route('project.transverses.complete', [$model->id]), '结项', '', ''));
                        //$actions->prepend(new TransverseCompletePost($actions));
                    }

                }

            } elseif ($model['review_status'] == 1) {
                $actions->disableAll();
            } elseif ($model['review_status'] == 2) {
                $actions->disableEdit();
            }
        });
        return $grid;
    }

    public function header(Grid $grid)
    {
        $grid->header(function (Builder $builder) {
            $year = request()->get('year') ?: date('Y');
            $end = Transverse::query()
                ->selectRaw('count(*) as count,sum(amount) as amount')
                ->where('state', 1)
                ->whereYear('end_time', $year)
                ->where('review_status', 1)->first();
            $sign = Transverse::query()
                ->selectRaw('count(*) as count,sum(amount) as amount')
                ->whereYear('sign_date', $year)
                ->where('review_status', 1)->first();
            $data = [
                '签订合同' => collect([$sign['amount'] ?? 0, $sign['count']])->implode('万(') . '个)',
                '结项合同' => collect([$end['amount'] ?? 0, $end['count']])->implode('万(') . '个)',
                '到账金额' => TransverseBill::query()->whereYear('pay_date', $year)->sum('amount') . '万'
            ];
            $title = $year . '年';
            return view('admin.statistics.common-table-header', compact('title', 'data'));
        });
    }

    public static function detail($model)
    {
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($model, function (Show $show) use ($model) {
            $show->panel()->view('component.show.tab-panel');
            $show->field('uuid', __('系统编号'));
            $show->field('name', __('合同名称'));
            $show->field('contract_type', __('合同类型'));
            $show->field('user_name', __('负责人'));
            $show->field('department.name', __('dept_name'));
            $show->field('amount', __('contract_amount'));
            $show->field('in_amount', __('received amount'));
            $show->field('domain', __('所属领域'));
            $show->field('sign_date', __('签订时间'));
            $show->field('sign_address', __('签订地点'));

            if ($model->file) {
                $show->field('file', '合同附件')->as(function ($val) {
                    return $val ? '下载' : '';
                })->link(file_custom_preview_url($model['file'], '(合同附件)' . $model['name']));
            }
            if ($model->file2) {
                $show->field('file2', '承诺书')->as(function ($val) {
                    return $val ? '下载' : '';
                })->link(file_custom_preview_url($model['file2'], '(承诺书)' . $model['name']));
            }
            if ($model['review_status']) {
                $show->field('review_remark', __('院级审批意见'));
            }
            if ($model['review_status'] == 1) {
                $show->field('state', __('状态'))->using(['在研', '已结项']);
            }
        }));
        if ($participants = $model['participants']) {
            $tab->add('参加人员', new Table(['姓名', '单位', '职称', '负责任务'], collect($participants)->values()->all()));
        }
        $tab->add('甲方信息', self::buyerDetail($model));
        $tab->add('到账记录', self::billDetail($model));
        $tab->add('日志', new Table(['标题', '操作人', '备注', '操作时间'], $model->logs()->orderByDesc('id')->get()
            ->map(function ($item) {
                return $item->only(['title', 'user_name', 'remark', 'created_at']);
            })->all()));
        return $tab;
    }

    public static function billDetail($model)
    {
        return new Table(['到账金额(万)', '到账时间', '创建时间'], $model->bills->map(function ($item) {
            return $item->only(['amount', 'pay_date', 'created_at']);
        })->all());
    }

    public static function buyerDetail($model)
    {
        return Admin::show($model, function (Show $show) use ($model) {
            $show->panel()->view('component.show.tab-panel');
            $show->field('buyer', __('buyer'));
            $show->field('buyer_fr', __('法人'));
            $show->field('buyer_unified_code', __('统一社会信用代码'));
            $show->field('buyer_person', __('buyer_person'));
            $show->field('buyer_phone', __('buyer_phone'));
            $show->field('buyer_province', __('buyer_province'));
            $show->field('buyer_address', __('buyer_address'));
        });
    }

    public function form(Form $form, $type = 0): Form
    {
        $user = Admin::user();
        $form->text('name', __('合同名称'))
            //->creationRules(['required', "unique:transverses"], ['required' => '不能为空', 'unique' => '合同名称已存在'])
            //->updateRules(['required', "unique:transverses,name,{{id}}"], ['required' => '不能为空', 'unique' => '合同名称已存在'])
            ->required();
        $form->radio('contract_type', __('合同类型'))->options(project_contract_type_options())->required();
        $form->text('buyer', __('甲方名称'))->required();
        $form->text('buyer_fr', __('甲方法人'))->required();
        $form->text('buyer_unified_code', __('统一社会信用代码'))->required();
        $form->text('buyer_person', __('甲方联系人'))->required();
        $form->text('buyer_phone', __('甲方联系电话'))->required();
        $form->select('buyer_province', '甲方所属省份')->options(Enum::province())->required();
        $form->text('buyer_address', __('甲方住址'))->required();
        $form->text('amount', __('contract_amount'))->required()->rules('numeric', ['numeric' => '请输入有效金额']);
//        $form->text('in_amount', __('received amount'))
//            ->default(0.00)
//            ->rules('numeric', ['numeric' => '请输入有效金额']);
        $form->select('domain', __('所属领域'))->options(project_technical_field_select_options());
        $form->date('sign_date', __('签订时间'))->required();
        $form->text('sign_address', __('签订地点'));
        $form->file('file', '合同附件')->hidePreview()->uniqueName()->required();
        if (config('settings.project.project_promise_enabled')) {
            $form->file('file2', '承诺书')->hidePreview()->uniqueName()->required()
                ->help(SettingService::transversePromiseTemplateATag());
        }
        if ($user->role_type == 1 && $type == 1) {
            $form->select('department_id', __('dept_name'))->options(department_select_options());
            $form->select('user_id', __('负责人'))->options(function ($id) {
                return AdminUser::query()->where('id', $id)->pluck('name', 'id');
            })->ajax(admin_route('api.searchUser'))->help('请输入姓名搜索')->default(0);
            $form->text('user_name', __('负责人备注'))->help('项目负责人无账号，可备注姓名');
            $form->radio('review_status', '审批')->options(['待审批', '通过', '退回'])->when(2, function (Form $form) {
                $form->textarea('review_remark', '审批备注');
            })->when(1, function ($form) {
                $form->radio('state', __('研究状态'))->options(['在研', '已结项'])->default(0);
            });
            $form->date('end_time', '结项时间');
        } else {
            $form->hidden('review_status', __('Review status'))->default(0);
            $form->hidden('review_remark', __('Review remark'));
            if ($form->isCreating()) {
                $form->hidden('department_id', __('Department id'))->default($user->department_id);
                $form->hidden('user_id', __('User id'))->default($user->id);
                $form->hidden('user_name', __('User id'))->default($user->name);
            }
        }
        if ($form->isCreating()) {
            $form->hidden('year', __(''));
            $form->hidden('serial_number', __(''));
            //$form->hidden('code', __(''));
            $form->hidden('uuid', __(''));
            $form->hidden('dept_review_status', __('Dept review status'))->default(1);
            $form->hidden('creator_id', __('Creator id'))->default($user->id);
        }
        $form->saving(function (Form $form) use ($user) {
            if ($form->isCreating()) {
                $form->year = date('Y');
                $form->serial_number = $this->repository->getSerialNumber($form->year);
                $form->uuid = $this->repository->getApplyNewCode($form->year, $form->serial_number);
                //$form->code = $form->uuid;
            }
            if ($form->review_status == 1) {
                $form->review_remark = '';
            }
            if ($user->role_type == 1) {
                if ($form->review_status != 1) {
                    $form->state = 0;
                }
                $form->user_id = $form->user_id ?: 0;
            } else {
                $form->review_status = 0;
            }
        });
        $form->saved(function (Form $form) {
            if (!$form->model()->user_name && $user = $form->model()->user) {
                $form->model()->user_name = $user->name;
                $form->model()->save();
            }
        });
        return $form;
    }

    public function repository(): TransverseRepository
    {
        return app(TransverseRepository::class);
    }

}
